<template>
  <div>
    <SupInput :InpList="inpList" :BtnList="btnList" @clickFn="btnFn"></SupInput>
    <Suptable
      :headerData="headerData"
      :tableData="tableData"
      :isPage="true"
      :border="true"
      :total="total"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      :current-page="pagenum"
      :pagesizeList="fenye"
      :pagesize="pagesize"
    >
      <template v-slot:opera="{ row }">
        <div>
          <el-button type="primary" @click="goEdit(row.row)" size="small"
            >编辑</el-button
          >
          <el-button type="danger" @click="godelete(row.row.id)" size="small"
            >删除</el-button
          >
        </div>
      </template>
    </Suptable>
    <div>
      <el-dialog
        :title="isEdit ? '编辑' : '新增'"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <div>
          <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="100px"
            class="demo-ruleForm"
          >
            <el-form-item label="用户名" prop="name" v-if="!isEdit">
              <el-input v-model="ruleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="ruleForm.email"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" prop="phone">
              <el-input v-model="ruleForm.phone"></el-input>
            </el-form-item>
            <el-form-item label="收货地址" class="city" prop="qu">
              <el-select
                v-model="ruleForm.shen"
                @change="changeCity()"
                clearable
              >
                <el-option
                  v-for="item in citydata"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
              <el-select
                :disabled="shidata.length == 0"
                v-model="ruleForm.shi"
                @change="changeCity1()"
                clearable
              >
                <el-option
                  v-for="item in shidata"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
              <el-select
                :disabled="qudata.length == 0"
                v-model="ruleForm.qu"
                clearable
              >
                <el-option
                  v-for="item in qudata"
                  :key="item.code"
                  :label="item.name"
                  :value="item.name"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="性别" prop="sex" v-if="!isEdit">
              <el-select v-model="ruleForm.sex" placeholder="请选择性别">
                <el-option
                  v-for="(item, index) in sexList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm('ruleForm')"
                >确定</el-button
              >
            </el-form-item>
          </el-form>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
// @/是src的根目录
import {
  AddressList,
  detAddress,
  queryAddress,
  addAddress,
  editAddress,
} from "@/api/AddressMock.js";
import Suptable from "@/components/Suptable";
import SupInput from "@/components/SupInput";
import citydata from "@/config/city.json";
export default {
  name: "userAddress",
  data() {
    let validatormail = (rule, value, callback) => {
      let myreg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!myreg.test(value.trim()) || value.trim() == "") {
        callback(new Error("请输入正确邮箱"));
      } else {
        callback();
      }
    };
    let validatorphone = (rlue, value, callback) => {
      let myreg =
        /^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/;
      if (!myreg.test(value.trim()) || value.trim() == "") {
        callback(new Error("请输入正确手机号"));
      } else {
        callback();
      }
    };
    return {
      pagenum: 1,
      pagesize: 10,
      total: 0,
      fenye: [5, 10, 15, 20],
      dialogVisible: false,
      isEdit: false,
      editId: "",
      tableData: [],
      citydata: citydata, //整个的数据数组
      shidata: [], //市数组
      qudata: [], //区数组
      inpList: [
        {
          text: "请输入用户名",
          model: "",
        },
        {
          text: "请输入有手机号",
          model: "",
        },
      ],
      btnList: [
        {
          icon: "el-icon-search",
          name: "查找",
        },
        {
          icon: "el-icon-edit",
          name: "添加",
        },
      ],
      sexList: [
        {
          label: "男",
          value: "1",
        },
        {
          label: "女",
          value: "2",
        },
      ],
      headerData: [
        {
          prop: "id",
          label: "用户ID",
          width: "100",
        },
        {
          prop: "username",
          label: "用户名",
          width: "150",
        },
        {
          prop: "gender",
          label: "性别",
          width: "100",
        },
        {
          prop: "phone",
          label: "电话",
          width: "150",
        },
        {
          prop: "email",
          label: "邮箱",
        },
        {
          prop: "address",
          label: "收货地址",
        },
      ],
      ruleForm: {
        id: "",
        name: "",
        email: "",
        sex: "",
        phone: "",
        shen: "",
        shi: "",
        qu: "",
      },
      rules: {
        name: [{ required: true, message: "请输入用户名称", trigger: "blur" }],
        email: [{ validator: validatormail, trigger: "blur", required: true }],
        phone: [{ required: true, trigger: "blur", validator: validatorphone }],
        sex: [{ required: true, message: "请输入性别", trigger: "blur" }],
        qu: [{ required: true, message: "请输完整", trigger: "blur" }],
      },
    };
  },
  mounted() {
    let _self = this;
    _self.addressList();
  },
  methods: {
    goEdit(row) {
      let _self = this;
      _self.isEdit = true;
      _self.dialogVisible = true;
      let arr = row.address.split(" ");
      _self.ruleForm = {
        email: row.email,
        phone: row.phone,
        shen: arr[0],
        shi: arr[1],
        qu: arr[2],
      };
      _self.$nextTick(() => {
        _self.$refs["ruleForm"].clearValidate();
      });
      _self.editId = row.id;
    },
    godelete(id) {
      let _self = this;
      _self
        .$confirm("确定删除吗", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(() => {
          let data = { id };
          detAddress(data).then((res) => {
            console.log(res);
            if (res.meta.status == 200) {
              _self.$message({
                type: "success",
                message: "删除成功",
              });
              _self.addressList();
            } else {
              _self.$message({
                type: "info",
                message: "res.meta.msg",
              });
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    addressList() {
      let _self = this;
      let data = {
        pagenum: _self.pagenum,
        pagesize: _self.pagesize,
      };
      AddressList(data).then((res) => {
        // console.log(res)
        let _self = this;
        _self.tableData = [];
        for (let item of res.data.user) {
          let addressData = {
            id: item.id,
            username: item.username,
            phone: item.phone,
            gender: item.gender == 0 ? "男" : "女",
            email: item.email,
            address: item.address,
          };
          _self.tableData.push(addressData);
        }
        _self.total = res.data.total;
        _self.pagenum = res.data.pagenum;
      });
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      let _self = this;
      _self.pagesize = val;
      _self.addressList();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let _self = this;
      _self.pagenum = val;
      _self.addressList();
    },
    btnFn(index) {
      let _self = this;
      if (index == 0) {
        let data = {
          username: _self.inpList[0].model,
          phone: _self.inpList[1].model,
        };
        queryAddress(data).then((res) => {
          console.log(res);
          _self.tableData = [];
          if (res.meta.status == 200) {
            for (let item of res.data.arr) {
              let addressData = {
                id: item.id,
                username: item.username,
                phone: item.phone,
                gender: item.gender == 0 ? "男" : "女",
                email: item.email,
                address: item.address,
              };
              _self.tableData.push(addressData);
              _self.total = res.data.total;
              _self.pagesize = res.data.pagesize;
            }
          } else {
            _self.pagesize = 10;
            _self.addressList();
          }
        });
      } else if (index == 1) {
        let _self = this;
        _self.isEdit = false;
        _self.dialogVisible = true;
        _self.ruleForm = {
          name: "",
          sex: "",
          phone: "",
          email: "",
          qu:"",
        };
         _self.$nextTick(() => {
        _self.$refs["ruleForm"].clearValidate();
      });
      }
    },
    changeCity() {
      let _self = this;
      _self.shidata = [];
      _self.qudata = [];
      _self.ruleForm.shi = "";
      _self.ruleForm.qu = "";
      console.log(_self.ruleForm.shen);
      for (let item of _self.citydata) {
        if (item.name == _self.ruleForm.shen) {
          _self.shidata = item.children;
        }
      }
    },
    changeCity1() {
      let _self = this;
      _self.qudata = [];
      _self.ruleForm.qu = "";
      for (let item of _self.shidata) {
        if (item.name == _self.ruleForm.shi) {
          _self.qudata = item.children;
        }
      }
    },
    submitForm(formName) {
      let _self = this;
      console.log(_self.ruleForm);
      _self.$refs[formName].validate((valid) => {
        if (valid) {
          let { name, sex, email, phone, shen, shi, qu } = _self.ruleForm;
          let address = shen + " " + shi + " " + qu;
          if (!_self.isEdit) {
            let data = {
              username: name,
              gender: sex,
              email,
              phone,
              address,
            };
            addAddress(data).then((res) => {
              // console.log(res);
              if (res.meta.status == "200") {
                _self.dialogVisible = false;
                _self.$refs[formName].resetFields();
                _self.addressList();
              } else {
                _self.$message(res.meta.msg);
              }
            });
          } else {
            let data = {
              id: _self.editId,
              email,
              phone,
              address,
            };
            console.log(data);
            editAddress(data).then((res) => {
              // console.log(res);
              if (res.meta.status == 200) {
                _self.addressList();
                _self.$message("更改成功");
                _self.dialogVisible = false;
                _self.$refs[formName].resetFields();
              }
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
  },
  components: { SupInput, Suptable },
};
</script>
<style>
.el-input {
  width: inherit;
}
.city .el-input {
  width: 150px;
}
</style>





















































































































































